package com.lemi.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lemi.dao.MenuMapper;
import com.lemi.dao.MenuOperationMapper;
import com.lemi.dao.RoleMapper;
import com.lemi.dao.RoleMenuMapper;
import com.lemi.entity.*;
import com.lemi.util.BspEntity;
import com.lemi.util.BspResult;
import com.lemi.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private MenuOperationMapper menuOperationMapper;

    @RequestMapping("list")
    public String list(Model model, BspEntity bspEntity){
        model.addAttribute("bspEntity",bspEntity);
        return "sys/role";
    }

    @RequestMapping("listData")
    @ResponseBody
    public Object listData(BspEntity bspEntity){
        try {
            Example ue = new Example(Role.class);
            Example.Criteria criteria = ue.createCriteria();
            criteria.andEqualTo("delFlag",false);

            if(StringUtils.isNotBlank(bspEntity.getRoleName())){
                criteria.andLike("roleName","%"+bspEntity.getRoleName()+"%");
            }

            PageHelper.startPage(bspEntity.getPage(),bspEntity.getLimit());
            PageHelper.orderBy(bspEntity.getOrderColumn()+" "+bspEntity.getOrderDir());

            List<Role> roles = roleMapper.selectByExample(ue);
            PageInfo<Role> orderPageInfo = new PageInfo<>(roles);
            bspEntity.setTotal(orderPageInfo.getTotal());
            bspEntity.setListData(roles);

            return BspResult.ok("",bspEntity);
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }


    @RequestMapping("edit")
    @ResponseBody
    public Object edit(HttpSession session, Role role){
        try {
            if(StringUtils.isBlank(role.getRoleName())){
                return BspResult.err("角色名称不能为空");
            }

            Example re = new Example(Role.class);
            Example.Criteria criteria = re.createCriteria();
            criteria.andEqualTo("delFlag",false).andEqualTo("roleName",role.getRoleName());

            if(role.getId()!=null){
                criteria.andNotEqualTo("id",role.getId());
            }

            List<Role> roles = roleMapper.selectByExample(re);
            if(roles.size()>0){
                return BspResult.err("角色已存在！");
            }

            User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);

            if(role.getId()==null){//新增
                role.setIsUse(1);
                role.setDelFlag(false);
                role.setVersion(0L);
                role.setCreateTime(new Date());
                role.setCreateName(loginUser.getUserName());
                roleMapper.insert(role);
            }else{
                role.setUpdateTime(new Date());
                role.setUpdateName(loginUser.getUserName());
                roleMapper.updateByPrimaryKeySelective(role);
            }
            return BspResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }


    @RequestMapping("isUse")
    public String isUse(HttpSession session, Model model, BspEntity bspEntity){
        if(bspEntity.getId()!=null){
            Example ue = new Example(User.class);
            ue.createCriteria().andEqualTo("delFlag",false).andEqualTo("id",bspEntity.getId());
            List<Role> roles = roleMapper.selectByExample(ue);
            if(roles.size()>0){
                User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);

                Role role = roles.get(0);
                Integer isUse = role.getIsUse();
                role.setIsUse(isUse==1?0:1);
                role.setUpdateTime(new Date());
                role.setUpdateName(loginUser.getUserName());
                roleMapper.updateByPrimaryKeySelective(role);
            }
        }
        model.addAttribute("bspEntity",bspEntity);
        return list(model,bspEntity);
    }


    @RequestMapping("menu")
    @ResponseBody
    public Object menu(Role role){
        try {
            List<RoleMenu> roleMenuIds = null;
            if(role.getId()!=null) {
                Example rme = new Example(RoleMenu.class);
                rme.createCriteria().andEqualTo("delFlag",false).andEqualTo("roleId",role.getId());
                roleMenuIds = roleMenuMapper.selectByExample(rme);
            }

            Example me = new Example(Menu.class);
            me.createCriteria().andEqualTo("delFlag",false).andEqualTo("status",0);
            List<Menu> menus =  menuMapper.selectByExample(me);

            Example moe = new Example(MenuOperation.class);
            moe.createCriteria().andEqualTo("delFlag",false).andEqualTo("status",0).andEqualTo("isLimit",1);
            List<MenuOperation> menuOperations = menuOperationMapper.selectByExample(moe);
            for (MenuOperation menuOperation : menuOperations) {
                String name = menuOperation.getName();
                if(name.startsWith("{") && name.endsWith("}")){
                    JSONObject jsonObject = JSONObject.parseObject(name);
                    name = jsonObject.get("trueResult") +"|"+jsonObject.get("falseResult");
                }
                menus.add(new Menu(menuOperation.getId(),name,menuOperation.getMenuId()));
            }

            JSONObject jo = new JSONObject();
            jo.put("roleMenuIds", roleMenuIds);
            jo.put("menus", menus);
            return BspResult.ok("",jo);
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }


    @RequestMapping("permission")
    @ResponseBody
    public Object permission(HttpSession session,Integer id,String checkedMenuIds){
        try {
            if(id==null){
                return BspResult.err("角色为空");
            }

            List<String> checkedIds = new ArrayList<>();
            List<Menu> checkedLeafMenus = null;

            if(StringUtils.isNotBlank(checkedMenuIds)){
                String[] split = checkedMenuIds.split(",");
                for (String menuId : split) {
                    if(Integer.parseInt(menuId)>100){//100以上的是operation
                        checkedIds.add(menuId);
                    }
                }

                Example me = new Example(Menu.class);
                me.createCriteria().andEqualTo("delFlag",false).andEqualTo("status",0)
                        .andNotEqualTo("menuUrl","").andIn("id", Arrays.asList(split));
                checkedLeafMenus = menuMapper.selectByExample(me);
            }

            if(checkedLeafMenus!=null && checkedLeafMenus.size()>0){
                for (Menu checkedLeafMenu : checkedLeafMenus) {
                    checkedIds.add(checkedLeafMenu.getId()+"");
                }
            }

            List<RoleMenu> insertMenus = new ArrayList<>();

            User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);
            Example rme = new Example(RoleMenu.class);
            rme.createCriteria().andEqualTo("delFlag",false).andEqualTo("roleId",id);
            List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(rme);

            outer:for (String checkedId : checkedIds) {
                for (RoleMenu roleMenu : roleMenus) {
                    if(roleMenu.getMenuId().equals(checkedId)){
                        continue outer;
                    }
                }
                insertMenus.add(new RoleMenu(id+"",checkedId,Integer.parseInt(checkedId)>100?2:1,0,new Date(),loginUser.getUserName()));
            }

            //批量插入角色菜单关联表
            if(insertMenus.size()>0){
                roleMenuMapper.insertBatch(insertMenus);
            }

            //取消的权限删除
            rme.clear();
            rme.createCriteria().andEqualTo("delFlag",false).andEqualTo("roleId",id).andNotIn("menuId",checkedIds);
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setDelFlag(true);
            roleMenu.setUpdateTime(new Date());
            roleMenu.setUpdateName(loginUser.getUserName());
            roleMenuMapper.updateByExampleSelective(roleMenu,rme);

            return BspResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }
}
